<template>
  <div>
    <navBar>
        <template v-slot:default>图书详情 -- {{id}}</template>
    </navBar>

  <!-- 商品图片 -->
  <van-image style="margin-top: 50px;"
    width="100%"
    lazy-load
    :src="detail.cover_url"
  />
  
  <!-- 商品卡片 -->
  <van-card style="text-align: left"
    :num="detail.stock"
    :price="detail.price+'.00'"
    :desc="detail.description"
    :title="detail.title"
  >
    <template #tags>
      <van-tag plain type="danger" >新书</van-tag>
      <van-tag plain type="danger" v-if="detail.is_recommend === 1 ? true:false">推荐</van-tag>
    </template>
    <template #footer>
      <van-button type="warning" @click="handleAddCart">添加购物车</van-button>
      <van-button type="danger" @click="goToCart">立即购买</van-button>
    </template>
  </van-card>

  <!-- 标签 -->
  <van-tabs v-model="active">
    <van-tab title="概述">
      <div class="content" v-html="detail.details">
        
      </div>
    </van-tab>
    <van-tab title="热评">
      <div class="comment">
          <br>空
      </div>
    </van-tab>
    <van-tab title="相关图书">
        <GoodsList :goods="like_goods"></GoodsList>
    </van-tab>
  </van-tabs>

  </div>
</template>

<script>
import GoodsList from 'components/content/goods/GoodsList.vue'
import navBar from 'components/common/navbar/NavBar.vue'
import { useRoute, useRouter} from 'vue-router'
import { useStore } from 'vuex'
import { ref, onMounted, reactive, toRefs } from 'vue'
import { getDetail } from 'network/detail.js'
import { addCart, } from '@/network/cart.js' 
import { Toast } from 'vant'

export default {
  name: 'Detail',
  components:{
    navBar,
    GoodsList
  },
  setup() {
    let active = ref(1)
    // 图书详情
    let book = reactive({
      detail: {},
      like_goods: [],
    })
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    let id = ref(0)

    // 获取商品详情数据
    onMounted(async ()=>{
      id.value = route.query.id
      const data = await getDetail(id.value)
      book.detail = data.goods
      book.like_goods = data.like_goods
    })

    // 加入购物车
    const handleAddCart = async ()=>{
      const data = await addCart({goods_id: book.detail.id, num: 1})
      if(data.status === 201 || data.status === 204) {
        Toast.success('添加成功')
        // 设置 store 中购物车的数量
        store.dispatch('updateCart')
      }
    }

    // 立即购买
    const goToCart = async () =>{
      const data = await addCart({goods_id: book.detail.id, num: 1})
      if(data.status === 201 || data.status === 204) {
        Toast.success('添加成功，前往购物车')
        store.dispatch('updateCart')
        router.push('/shopcart')

      }
    }
    
    return {
      id,
      ...toRefs(book),
      active,
      handleAddCart,
      goToCart
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding: 10px;
  img {
    max-width: 100%;
    height: auto;
  }
}
.comment {
  height: 200px;
}

</style>